﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace UDP发送端
{
    public partial class Form1 : Form
    {
        private UdpClient udpClient;

        public Form1()
        {
            InitializeComponent();

            // 初始化窗体显示数据
            initFormData();
        }

        // 初始化窗体显示数据
        private void initFormData()
        {
            textBox1.Text = Properties.Settings.Default.ipAddress;
        }

        // 初始化Udp客户端
        private void initUdpClient()
        {
            try
            {
                int clientPort = Properties.Settings.Default.clientPort;

                // 如果配置文件中源端口号不为0，那么就绑定用户指定的源端口，否则自动分配
                if (clientPort == 0)
                {
                    // 创建UdpClient实例自动分配源端口
                    udpClient = new UdpClient();
                }
                else
                {
                    // 创建UdpClient实例并绑定到本地的特定源端口
                    udpClient = new UdpClient(clientPort);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "警告", MessageBoxButtons.OK, MessageBoxIcon.Error);

                // 创建实例对象失败，则退出程序
                //Application.Exit();
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void Form1_Shown(object sender, EventArgs e)
        {
            // 初始化Udp客户端
            initUdpClient();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            // 获取richtextbox中的十六进制数据和服务器IP地址
            string hexData = richTextBox1.Text.Replace(" ", ""); // 去除空格
            string serverIp = textBox1.Text.Replace(" ", ""); // 这里填写实际的服务器IP地址

            // 获取指定的接收端端口
            int serverPort = Properties.Settings.Default.serverPort;

            // 调用发送方法
            SendUdpData(hexData, serverIp, serverPort);
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            // 保存最后一次IP地址
            Properties.Settings.Default.ipAddress = textBox1.Text;
            Properties.Settings.Default.Save();

            // 关闭时释放资源
            if (udpClient != null)
            {
                udpClient.Close();
            }
        }

        // 封装UDP发送方法，接受十六进制字符串作为输入
        private void SendUdpData(string hexData, string serverIp, int serverPort)
        {
            try
            {
                byte[] dataBytes = StringToByteArray(hexData);

                // 创建远程终结点
                IPEndPoint endPoint = new IPEndPoint(IPAddress.Parse(serverIp), serverPort);

                // 发送数据
                udpClient.Send(dataBytes, dataBytes.Length, endPoint);

                MessageBox.Show("Data sent successfully.");
            }
            catch (Exception ex)
            {
                MessageBox.Show($"Error sending data: {ex.Message}");
            }
        }

        // 十六进制字符串转字节数组的方法
        private static byte[] StringToByteArray(string hex)
        {
            int numberChars = hex.Length;
            byte[] bytes = new byte[numberChars / 2];
            for (int i = 0; i < numberChars; i += 2)
            {
                bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16);
            }
            return bytes;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            // 打开端口选择窗口
            PortSelectForm portSelectForm = new PortSelectForm();
            portSelectForm.ShowDialog();
        }

        private void button3_Click(object sender, EventArgs e)
        {
            Author author = new Author();
            author.ShowDialog();
        }
    }
}
